<template>
	<view class="container">
		<!-- 顶部选项卡 -->
		<view class="tabs-section">
			<u-tabs :list="list" :current="currentTab" @click="changeStatus"
				:activeStyle="{color: '#2979ff', fontWeight: 'bold'}" :inactiveStyle="{color: '#606266'}"
				lineColor="#2979ff" itemStyle="padding-left: 15px; padding-right: 15px; height: 44px;"></u-tabs>
		</view>

		<!-- 内容区域 -->
		<view class="content">
			<!-- 加载状态 -->
			<u-loading-page :loading="isLoading" loading-text="加载中..." loading-mode="semicircle"
				iconSize="40"></u-loading-page>

			<!-- 空状态 -->
			<view v-if="!isLoading && orderList.length === 0" class="empty-state">
				<image class="empty-image" src="https://www.taotaohomecraft.press/prod-api/profile/non_order.png"
					mode="aspectFit"></image>
				<text class="empty-text">暂无订单</text>
				<text class="empty-desc">当前状态下没有相关订单</text>
			</view>

			<!-- 订单列表 -->
			<scroll-view v-else class="order-list" scroll-y="true" @scrolltolower="onReachBottom">
				<view class="order-item" v-for="(item, index) in orderList" :key="item.id">
					<!-- 订单头部 -->
					<view class="order-header" @click="handleOrderDetail(item.id)">
						<view class="order-no">
							<text class="order-no-label">订单编号：</text>
							<text class="order-no-value">{{item.id}}</text>
						</view>
						<view class="order-status">
							<text
								:class="['status-text', `status-${item.status}`]">{{getStatusText(item.status)}}</text>
						</view>
					</view>

					<!-- 订单内容 -->
					<view class="order-content" @click="handleOrderDetail(item.id)">
						<view class="book-list">
							<view class="book-cover" v-for="(book, bookIndex) in item.bookList" :key="book.id">
								<image class="book-image"
									:src="book.photo || 'https://www.taotaohomecraft.press/prod-api/profile/non-photo.png'"
									mode="aspectFill"></image>
								<view v-if="bookIndex === 2 && item.bookList.length > 3" class="book-more">
									<text class="more-text">+{{item.bookList.length - 3}}</text>
								</view>
							</view>
						</view>
						<view class="order-info">
							<text class="book-count">共{{item.bookList.length}}本</text>
							<text class="expire-tip" v-if="item.status === '3' && item.expireDays <= 3">
								距离还书还剩{{item.expireDays}}天
							</text>
						</view>
					</view>

					<!-- 订单操作 -->
					<view class="order-actions">
						<view v-if="item.status === '3'" class="action-btn">
							<u-button type="primary" text="去还书" :plain="true" size="mini" :customStyle="btnStyle"
								@click="handleOpenShow(item.id, '4', '是否确认还书？')">
							</u-button>
						</view>
						<view v-if="item.status === '0' || item.status === '2'" class="action-btn">
							<u-button type="primary" color="#19be6b" text="确认收货" :plain="true" size="mini"
								:customStyle="btnStyle" @click="handleOpenShow(item.id, '3', '是否确认收货？')">
							</u-button>
						</view>
						<view v-if="item.status === '0' || item.status === '1'" class="action-btn">
							<u-button type="primary" color="#fa3534" text="取消订单" :plain="true" size="mini"
								:customStyle="btnStyle" @click="handleOpenShow(item.id, '6', '是否取消该订单？')">
							</u-button>
						</view>
					</view>
				</view>

				<!-- 加载更多 -->
				<view v-if="orderList.length > 0" class="load-more">
					<text class="load-more-text">{{hasMore ? '上拉加载更多' : '没有更多数据了'}}</text>
				</view>
			</scroll-view>
		</view>

		<!-- 操作确认弹窗 -->
		<u-modal :content="content" :show="show" showCancelButton closeOnClickOverlay :confirmColor="confirmColor"
			@confirm="confirmReturnBook()" @cancel="cancelShow()" @close="cancelShow()">
		</u-modal>
	</view>
</template>

<script>
	import {
		bookOrderList,
		updateStatus
	} from '@/api/order.js';
	import {
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import config from '@/config';

	export default {
		data() {
			return {
				content: '',
				orderId: '',
				show: false,
				currentTab: 0,
				list: [{
						name: '全部',
						value: '999'
					}, {
						name: '待取书',
						value: '0'
					},
					{
						name: '待配送',
						value: '1'
					},
					{
						name: '配送中',
						value: '2'
					}, {
						name: '借阅成功',
						value: '3'
					}, {
						name: '待还书',
						value: '4'
					}, {
						name: '已还书',
						value: '5'
					}
				],
				isLoading: false,
				status: '999',
				orderList: [],
				pageNum: 1,
				pageSize: 10,
				total: 0,
				hasMore: true,
				btnStyle: {
					width: '140rpx',
					height: '60rpx',
					fontSize: '24rpx'
				},
				confirmColor: '#2979ff'
			}
		},
		onLoad() {
			this.getList()
		},
		onPullDownRefresh() {
			this.pageNum = 1
			this.hasMore = true
			this.getList().then(() => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom() {
			if (this.hasMore && !this.isLoading) {
				this.pageNum++
				this.getList(true)
			}
		},
		methods: {
			async getList(isLoadMore = false) {
				this.isLoading = true
				try {
					const params = {
						status: this.status,
						pageNum: this.pageNum,
						pageSize: this.pageSize
					}

					const res = await bookOrderList(params)
					if (res.code === 200) {
						const newList = res.rows || []

						// 处理图片URL
						newList.forEach(item => {
							item.bookList.forEach(book => {
								if (book.photo) {
									book.photo = config.baseUrl + book.photo
								}
							})

							// 模拟到期天数
							item.expireDays = Math.floor(Math.random() * 10) + 1
						})

						if (isLoadMore) {
							this.orderList = [...this.orderList, ...newList]
						} else {
							this.orderList = newList
						}

						this.total = res.total || 0
						this.hasMore = this.orderList.length < this.total
					} else {
						uni.showToast({
							title: res.msg || '获取订单列表失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取订单列表失败:', error)
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					})
				}
				this.isLoading = false
			},
			changeStatus(item) {
				this.currentTab = item.index
				this.status = item.value
				this.pageNum = 1
				this.hasMore = true
				this.getList()
			},
			getStatusText(status) {
				const statusMap = {
					'0': '待取书',
					'1': '待配送',
					'2': '配送中',
					'3': '借阅成功',
					'4': '待还书',
					'5': '已还书',
					'6': '已取消'
				}
				return statusMap[status] || '未知状态'
			},
			handleOpenShow(id, status, content) {
				this.orderId = id
				this.show = true
				this.content = content
				this.status = status

				// 根据操作类型设置确认按钮颜色
				if (status === '6') {
					this.confirmColor = '#fa3534' // 取消订单用红色
				} else {
					this.confirmColor = '#2979ff' // 其他操作用蓝色
				}
			},
			cancelShow() {
				this.show = false
			},
			async confirmReturnBook() {
				try {
					const res = await updateStatus(this.status, this.orderId)
					if (res.code === 200) {
						uni.showToast({
							title: '操作成功',
							icon: 'success'
						})
						this.show = false
						this.pageNum = 1
						this.getList()
					} else {
						uni.showToast({
							title: res.msg || '操作失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('操作失败:', error)
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					})
				}
			},
			handleOrderDetail(orderId) {
				uni.navigateTo({
					url: `/order/orderDetail/index?orderId=${orderId}`
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background: linear-gradient(180deg, #f6f9ff 0%, #f0f4ff 100%);
	}

	.tabs-section {
		background-color: #ffffff;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.content {
		flex: 1;
		display: flex;
		flex-direction: column;
		padding: 20rpx 24rpx;
	}

	.empty-state {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 60rpx 40rpx;
	}

	.empty-image {
		width: 300rpx;
		height: 300rpx;
		opacity: 0.8;
	}

	.empty-text {
		font-size: 32rpx;
		color: #909399;
		margin-top: 40rpx;
		font-weight: 500;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #c0c4cc;
		margin-top: 16rpx;
	}

	.order-list {
		flex: 1;
	}

	.order-item {
		background: #ffffff;
		border-radius: 20rpx;
		margin-bottom: 24rpx;
		padding: 30rpx;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.04);
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;

		&:active {
			transform: translateY(2rpx);
			box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
		}

		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			width: 8rpx;
			height: 100%;
			background: linear-gradient(180deg, #2979ff 0%, #5cadff 100%);
			border-radius: 4rpx 0 0 4rpx;
		}
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f4ff;
	}

	.order-no {
		display: flex;
		align-items: center;
	}

	.order-no-label {
		font-size: 26rpx;
		color: #909399;
	}

	.order-no-value {
		font-size: 26rpx;
		color: #303133;
		font-family: 'Courier New', monospace;
		font-weight: 500;
	}

	.order-status {
		.status-text {
			font-size: 24rpx;
			font-weight: 500;
			padding: 8rpx 16rpx;
			border-radius: 20rpx;
		}

		.status-0 {
			color: #e6a23c;
			background: #fdf6ec;
		}

		.status-1,
		.status-2 {
			color: #409eff;
			background: #ecf5ff;
		}

		.status-3 {
			color: #67c23a;
			background: #f0f9eb;
		}

		.status-4 {
			color: #f56c6c;
			background: #fef0f0;
		}

		.status-5 {
			color: #909399;
			background: #f4f4f5;
		}

		.status-6 {
			color: #909399;
			background: #f4f4f5;
			text-decoration: line-through;
		}
	}

	.order-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.book-list {
		display: flex;
		flex: 1;
	}

	.book-cover {
		width: 120rpx;
		height: 160rpx;
		margin-right: 20rpx;
		border-radius: 12rpx;
		overflow: hidden;
		position: relative;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

		&:last-child {
			margin-right: 0;
		}
	}

	.book-image {
		width: 100%;
		height: 100%;
	}

	.book-more {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.6);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.more-text {
		color: #ffffff;
		font-size: 28rpx;
		font-weight: bold;
	}

	.order-info {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.book-count {
		font-size: 28rpx;
		color: #606266;
		margin-bottom: 12rpx;
		font-weight: 500;
	}

	.expire-tip {
		font-size: 24rpx;
		color: #e6a23c;
		background: #fdf6ec;
		padding: 6rpx 16rpx;
		border-radius: 12rpx;
	}

	.order-actions {
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;
		padding-top: 20rpx;
		border-top: 1rpx solid #f0f4ff;
	}

	.action-btn {
		// 按钮样式已在组件中定义
	}

	.load-more {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx 0;
	}

	.load-more-text {
		font-size: 26rpx;
		color: #909399;
	}
</style>